<?php

namespace App\Backend\Service;

use App\Models\Baoliaopost;
use App\Exceptions\InvalidRequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Backend\Service\BaseService;
use App\Http\Service\SiteConfigService;

class ProductcategoryparentService extends BaseService
{

    private $model;

    public function __construct(Baoliaopost $model,SiteConfigService $siteConfigService)
    {
        parent ::__construct();
        $this->model = $model;
        $this->siteConfigService=$siteConfigService;
    }

     /**
     * 列表
     */
    public function getList($request,$data=[])
    {
        $page = intval($request->input('page')) ?$request->input('page') :$this->cpage;
        $limit = intval($request->input('limit')) ?$request->input('limit') :$this->climit;
        $offset = ($page-1)*$limit;
        //dd($data);
        $where = [];
        if($data['title']){
            $where[]=['title','like','%'.$data['title'].'%'];
        }

        if($data['start_date']){
            $where[]=['update_time','>=',$data['start_date']];
        }
        if($data['end_date']){
            $where[]=['update_time','<=',$data['end_date']];
        }
        
        if($data['check_status']){
            $where[]=['check_status','=',$data['check_status']];
        }

        if($data['check_result']){
            $where[]=['check_result','=',$data['check_result']];
        }

        if($data['channel']){
            $where[]=['channel','=',$data['channel']];
        }

        //dd($where);
        $count = $this->model->where($where)->count();
        $fields = ['*'];
        $list = $this->model->select($fields)
        ->where($where)
        ->offset($offset)->limit($limit)
        ->orderBy('id', 'desc')->get()->toArray();
        foreach ($list as  &$v){
            $channel=$v['channel'];
            
            $v['content_books'] =json_decode($v['content_books'],true);
            $v['images'] =json_decode($v['images'],true);   
            $v['guanlian_shop'] =json_decode($v['guanlian_shop'],true);   
        }
       
        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result;
    }

    /**
     * 详情
     */

    public function detail($request,$unique_id){
       $where = [
           ['unique_id','=',$unique_id],
        ];
        $list = $this->model->where($where)->first();;
        if(!empty($list)){
            $list['content_books'] =json_decode($list['content_books'],true);
            $list['images'] =json_decode($list['images'],true);   
            $list['guanlian_shop'] =json_decode($list['guanlian_shop'],true);   
        }

        
        return $list;
    }
      /**
     * 添加
     */
    public function add($request,$data)
    {
        /*        爆料和逛逛当天24点结束（优惠不一定会过期，只是其他人可以重新发布这个商品的爆料了），比如一个商品(平台+商品id)在今天有人上传了，那么到24点之前再有人上传，则提示该商品已被其他人爆料，引导去评论 过了24点后，这个商品可以重新被爆料上传*/

        $jsonData = $request->json()->all();
        $data['json_data']=json_encode($jsonData, JSON_UNESCAPED_UNICODE);
        $platform_name=$data['platform_name'];
        $product_unique_id=$data['product_unique_id'];

        
        $first=$this->model->where(['platform_name'=>$platform_name,'product_unique_id'=>$product_unique_id,'is_expired'=>2])->first();
        if($first){
            // 获取当前时间
            $currentTime =  time();

            // 判断是否显示警告
            if ($currentTime >= strtotime($first['start_time']) && 
                $currentTime <= strtotime($first['end_time'])){
                //商品未过期
                $this->error("该商品已被其他人爆料,可以去评论");
            }else{
                $unique_id=$first['unique_id'];
                $data3=[];
                $data3['create_time'] =date("Y-m-d H:i:s");
                $data3['is_expired'] =1;//过期
                $this->model->where(['unique_id'=>$unique_id])->update($data3);
            }

        }
        #判断上传的帖子的开始时间和结束时间  结束时间不能小于发布时间
        $currentTime =  time();
        if ($currentTime < strtotime($data['start_time']) || 
            $currentTime > strtotime($data['end_time'])){
            //商品未过期
            $this->error("[开始时间和结束时间已经结束]结束时间不能小于发布时间");
        }
        #修改默认值
        $type=$data['type'];
        $siteConfig=$this->siteConfigService->getList('4');
        $view_count=$siteConfig['content']['view_count'];
        if(in_array($type,['2','4'])){
            $data['view_count'] =$view_count;
        }
        if(empty($data['view_count'])){
            $data['view_count'] =0;
        }
        
        //dd($data);
        
        #添加数据
        $data['create_time'] =date("Y-m-d H:i:s");
        $data['update_time'] =date("Y-m-d H:i:s");

        $res=$post_id=$this->model->insertGetId($data);


        if($res){
            $this->success();
        }else{
            $this->error();
        }

    }

    /**
     * 编辑
     */
    public function edit($request,$data,$unique_id)
    {
        $res = $this->model->where('unique_id',$unique_id)->first();
        if(!$res) {
            $this->error('内容不存在');
        }
        $check_result=$data['check_result'];
        //同意 check_status
        if($check_result=='1'){
            $data['status']='1';
            $data['check_status']='3';

        }
        //拒绝
        if($check_result=='3'){
            $data['status']='2';
            $data['check_status']='3';


        }
        $data['update_time'] = date("Y-m-d H:i:s");

        $res =  $this->model->where('unique_id',$unique_id)->update($data);
        if(!$res){
            $this->error('修改失败');
        }else{
            $this->success();
        }
    }   

     /**
     * 删除
     */
    public function del($ids)
    {
        $res =  $this->model->whereIn('unique_id',$ids)->delete();
        if(!$res){
            $this->error('删除失败');
        }else{
            $this->success();
        }
    }   
    


}
